Contents
  1. 1. Generator.java:
  2. 2. 实例1:
    1. 2.1. Coffee.java:
    2. 2.2. Latte.java:
    3. 2.3. Mocha.java:
    4. 2.4. CoffeeGenerator.java:
  3. 3. 实例2:

泛型应用 Generator生成器 用于创建对象

Generator.java:

1
2
3
4
5
package lianxi;

public interface Generator<T> {
T RandomNext();
}

实例1:

Coffee.java:

1
2
3
4
5
6
7
8
9
10
package lianxi;

public class Coffee {
private static long counter = 0;
private final long id = counter++;
public String toString()
{

return getClass().getSimpleName() + " " + id;
}
}

Latte.java:

1
2
3
4
5
package lianxi;

public class Latte extends Coffee{

}

Mocha.java:

1
2
3
4
5
package lianxi;

public class Mocha extends Coffee{

}

CoffeeGenerator.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package lianxi;

import java.util.Iterator;
import java.util.Random;

public class CoffeeGenerator implements Generator<Coffee>, Iterable<Coffee>{

private Class[] types = {Latte.class, Mocha.class};//咖啡的种类
private static Random rand = new Random(47);
public CoffeeGenerator() {}

//For iteration: //实现了Iterable接口,所以可以在循环语句中使用它,不过需要一个末尾哨兵,所以实现了第2个构造器
private int size = 0;
public CoffeeGenerator(int size)
{

this.size = size;
}
public Coffee RandomNext()
{

try{//返回一个随机咖啡种类的实例
return (Coffee) types[rand.nextInt(types.length)].newInstance();
}catch(Exception e){
throw new RuntimeException(e);
}
}

class CoffeeIterator implements Iterator<Coffee>{
int count = size;
public boolean hasNext(){ return count > 0;}
public Coffee next(){
count--;
return CoffeeGenerator.this.RandomNext();
}
public void remove(){
throw new UnsupportedOperationException();
}
};

@Override
public Iterator<Coffee> iterator(){
return new CoffeeIterator();
}

public static void main(String[] arges){
CoffeeGenerator gen = new CoffeeGenerator();
for(int i = 0; i < 5; i++)
System.out.println(gen.RandomNext());
System.out.println("----------------");
for(Coffee c : new CoffeeGenerator(5))
System.out.println(c);
}
}
输出:
Mocha 0
Latte 1
Mocha 2
Latte 3
Latte 4
----------------
Mocha 5
Latte 6
Latte 7
Mocha 8
Mocha 9

实例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package lianxi;

public class Fibonacci implements Generator<Integer>{

private int count = 0;

public Fibonacci() {}

public Integer RandomNext()
{

return fib(count++);
}

public int fib(int n)
{

if(n < 2) return 1;
return fib(n - 1) + fib(n - 2);
}

public static void main(String[] args)
{

Fibonacci gen = new Fibonacci();
for(int i = 0; i < 18; i++)
System.out.print(gen.RandomNext() + " ");
}

}
输出:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
Contents
  1. 1. Generator.java:
  2. 2. 实例1:
    1. 2.1. Coffee.java:
    2. 2.2. Latte.java:
    3. 2.3. Mocha.java:
    4. 2.4. CoffeeGenerator.java:
  3. 3. 实例2: